
<div class="guigemero">
    <div class="guigebox">
        <div class="close"><img src="<?php echo $this->staticUrl?>img/png/pic98.png" alt=""></div>
        <div class="title">
            <div class="imgbox"><img id="img_zyl" src="<?php echo $this->staticUrl?>img/jpg/pic4.jpg" alt=""></div>
            <div class="fontcons">
                <span class="hongzi dk f13 lh10"><b class="f07 mr5">¥</b><c id="price_zyl">39.90</c></span>
                <span class="f08 cor9 dk">库存：<c id="quantity_zyl">23</c></span>
            </div>
        </div>
        <div class="p3 bor_bt info_zyl"></div>
        <div class="vCenter p3p">
            <span class="f09 cor6">购买数量</span>
            <div class="zengjian guige">
                <div class="min"></div>
                <div class="zi">1</div>
                <div class="add"></div>
            </div>
        </div>
        <a href="javascript:" class="kbtn submit_zyl">确定</a>
    </div>
</div>
<div class="jiazai" style="position:fixed;left:0;top:0;right:0;bottom:0;background:rgba(255,255,255,0);z-index:999;display:none;">
    <div class="jdjz pos" style="left:0;top:0;right:0;bottom:0">
        <img src="<?php echo $this->staticUrl?>layer/theme/default/loading-2.gif" />
    </div>
</div>
<script type="text/javascript">
    var swiper = new Swiper('.shopbanner');
    var base,choice = {},number2 = 1;
    var merchantId = '<?php echo $_GET['merchant_id']?>';
    $(function(){
        var toggle = $('#ss_toggle');
        var menu = $('#ss_menu');
        var rot;
        $('#ss_toggle').on('click', function (ev) {
            rot = parseInt($(this).data('rot')) - 180;
            menu.css('transform', 'rotate(' + rot + 'deg)');
            menu.css('webkitTransform', 'rotate(' + rot + 'deg)');
            if (rot / 180 % 2 == 0) {
                toggle.parent().addClass('ss_active');
                toggle.addClass('close');
            } else {
                toggle.parent().removeClass('ss_active');
                toggle.removeClass('close');
            }
            $(this).data('rot', rot);
        });
        menu.on('transitionend webkitTransitionEnd oTransitionEnd', function () {
            if (rot / 180 % 2 == 0) {
                $('#ss_menu div i').addClass('ss_animate');
            } else {
                $('#ss_menu div i').removeClass('ss_animate');
            }
        });

        //规格弹框控制
        $("body").on("touchstart",".zj>.guige",function(){
            //请求获取标签
            var productId = $(this).parent('.zj').attr('data-id');
            $.post("<?php echo getUrl('product/getProductProperty')?>",{product_id:productId},function(data){
                if(typeof data == 'string'){
                    base = data = JSON.parse(data);
        			console.log(data)
                    $('#img_zyl').attr('src',data.data.icon);
                    $('#price_zyl').text(data.data.price);
                    $('#quantity_zyl').text(data.data.quantity);
                    $('.info_zyl').html(data.data.html)
                }

            });
            $(".guigemero").animate({top:'0'});
        });

        //提交
        $("body").on("touchstart",".submit_zyl",function(){

            //过滤是否为空
            if(JSON.stringify(choice) == '{}'){
                show_message({status:0, message:'请选择属性'});
                return false;
            }
            if(tags.length){

                var addTags = skipEmptyElementForArray(choice.add.tags.split("|"))
                if(addTags.length!=tags.length){
                    show_message({status:0, message:'请选择属性'});
                    return false;
                }
                var editTags = skipEmptyElementForArray(choice.edit.tags.split("|"))
                if(editTags.length!=tags.length){
                    show_message({status:0, message:'请选择属性'});
                    return false;
                }
                var dataTags = skipEmptyElementForArray(choice.data.tags.split("|"))
                if(dataTags.length!=tags.length){
                    show_message({status:0, message:'请选择属性'});
                    return false;
                }
            }

            //数量是否合格
            if(number2 <= 0){
                show_message({status:0, message:'数量不对'});
                return false;
            }
            var  quantity = $(".guigebox").find('.zi').html();
           if(!(choice.add.sort > 0)){
               choice.add.sort = 0;
           }
            addMoel(choice.add.product_id, choice.add.sort, quantity, 1, 2,'',choice.add.tags);
        });

        var isTop = true;
        $("#shopcarbtn").on('click',function () {
            console.log($(".shopcar li").length);
            if($(".shopcar li").length==0){
                return false;
            }else{
                shopCarBtn();
            }
            
        });

        function shopCarBtn() {
            $(".shopcar").show();
            isTop = !isTop;
            var boxheight = $(".shopcar").height();
            if(isTop==true){
                $(".zezao").fadeOut(300);
                $(".shopcar").animate({
                    bottom: -boxheight
                });
            }else{
                $(".zezao").fadeIn(300);
                $(".shopcar").animate({
                    bottom: '49px'
                });
            }
            //            console.log(isTop);
        }
        /**
         * <pre>
         * @param arr
         * @returns {Array} 如果arr中的元素存在空字符串''，则去掉该空字符串
         * </pre>
         */
        function skipEmptyElementForArray(arr){
            var a = [];
            $.each(arr,function(i,v){
                var data = $.trim(v);//$.trim()函数来自jQuery
                if('' != data){
                    a.push(data);
                }
            });
            return a;
        }
        /**
         * 规格 - 点击添加减少
         */
        //购物车逻辑
        $("body").delegate(".guige>.add","touchstart",function () {
            var html = '<span class="min"></span><span class="zi">1</span>';
            if($(this).siblings(".zi").length==0){
                $(this).parents(".zengjian").prepend(html);
            }else {
                var thisnumber = $(this).siblings(".zi").text();
                $(this).siblings(".zi").text(parseInt(thisnumber)+1);
            }
        });

        $("body").delegate(".guige>.min","touchstart",function () {
            var zi = $(this).siblings(".zi");
            if(zi.text() == "1"){
                return;
            }else{
                var thisnumber = $(this).siblings(".zi").text();
                $(this).siblings(".zi").text(parseInt(thisnumber)-1);
            }

        });

        /**
         * 商品详情点击添加
         */
        $(".shopcarbox").delegate(".add","click",function () {

            var html = '<span class="min"></span><span class="zi">1</span>';
            heightmol();
            var s = "<?php echo $submit?>",
                zj = $(this).parent('.zj'),
                product_id = zj.attr('data-id'),
                sort = zj.attr('data-sort'),
                quantity = $(this).prev().html();
            if (sort == 0){
                sort = '';
            }
//            if($(this).siblings(".zi").length==0){
//                $(this).parents(".zengjian").prepend(html);
//            }else {
//                var thisnumber = $(this).siblings(".zi").text();
//                $(this).siblings(".zi").text(parseInt(thisnumber)+1);
//            }
            if (s){
                if (quantity == undefined){
                    quantity = 1;
                    $(this).parents(".zj").prepend(html);
                }else{
                    quantity = parseInt(quantity);
                    quantity = quantity+1;
                }

                addMoel(product_id, sort, quantity, 1, 0, $(this));
            }else{
                quantity = 1;
                addMoel(product_id, sort, quantity, 1, 2, $(this));
            }
			//shopCarBtn();
        });

        /**
         * 点击添加
         */
		 var clicktag = 0;
        $(".zengjian").delegate(".add","click",function () {
			if (clicktag == 0) {
				clicktag = 1;
				var html = '<span class="min"></span><span class="zi">1</span>';
				heightmol();
				var s = "<?php echo $submit?>",
					zj = $(this).parent('.zengjian'),
					product_id = zj.attr('data-id'),
					sort = zj.attr('data-sort'),
					quantity = $(this).prev().html();
				if (sort == 0){
					sort = '';
				}
	//            if($(this).siblings(".zi").length==0){
	//                $(this).parents(".zengjian").prepend(html);
	//            }else {
	//                var thisnumber = $(this).siblings(".zi").text();
	//                $(this).siblings(".zi").text(parseInt(thisnumber)+1);
	//            }
				if (s){
					var first = false;
					if (quantity == undefined){
						quantity = 1;
						first = true;
	//                    $(this).parents(".zengjian").prepend(html);
					}else{
						quantity = parseInt(quantity);
						quantity = quantity+1;
					}

					addMoel(product_id, sort, quantity, 1, 0, $(this), '', first);
				}else{
					quantity = 1;
					addMoel(product_id, sort, quantity, 1, 2, $(this));
				}
				//shopCarBtn();
				setTimeout(function () { 
					clicktag = 0
				}, 500);
			}
        });
		/**
         * 点击添加
         */
        $(".shopcar").delegate(".add","click",function () {

            var html = '<span class="min"></span><span class="zi">1</span>';
            heightmol();
            var s = "<?php echo $submit?>",
                zj = $(this).parent('.zengjian'),
                product_id = zj.attr('data-id'),
                sort = zj.attr('data-sort'),
                quantity = $(this).prev().html();
            if (sort == 0){
                sort = '';
            }
//            if($(this).siblings(".zi").length==0){
//                $(this).parents(".zengjian").prepend(html);
//            }else {
//                var thisnumber = $(this).siblings(".zi").text();
//                $(this).siblings(".zi").text(parseInt(thisnumber)+1);
//            }
            if (s){
                if (quantity == undefined){
                    quantity = 1;
                    $(this).parents(".zengjian").prepend(html);
                }else{
                    quantity = parseInt(quantity);
                    quantity = quantity+1;
                }

                addMoel(product_id, sort, quantity, 1, 0, $(this));
            }else{
                quantity = 1;
                addMoel(product_id, sort, quantity, 1, 2, $(this));
            }
			//shopCarBtn();
        });

        /**
         * 点击减少
         */
        $(".zengjian").delegate(".min","click",function () {
            var  zj = $(this).parent('.zengjian'),
                product_id = zj.attr('data-id'),
                sort = zj.attr('data-sort');
            if (sort == 0){
                sort = '';
            }
            if ($(this).siblings(".zi").text() <= 0){
                return;
            }
            if($(this).siblings(".zi").text() == "1"){
                deleteCart(product_id, sort);
            }else{
                var thisnumber = $(this).siblings(".zi").text();
                $(this).siblings(".zi").text(parseInt(thisnumber)-1);
                addMoel(product_id, sort, $(this).next().html(), 2, 0);
            }
        });
		/**
         * 点击减少
         */
        $(".shopcar").delegate(".min","click",function () {
            var  zj = $(this).parent('.zengjian'),
                product_id = zj.attr('data-id'),
                sort = zj.attr('data-sort');
            if (sort == 0){
                sort = '';
            }
            if ($(this).siblings(".zi").text() <= 0){
                return;
            }
            if($(this).siblings(".zi").text() == "1"){
                deleteCart(product_id, sort);
            }else{
                var thisnumber = $(this).siblings(".zi").text();
                $(this).siblings(".zi").text(parseInt(thisnumber)-1);
                addMoel(product_id, sort, $(this).next().html(), 2, 0);
            }
        });
		
		//点击灰色背景
		$("body").delegate(".zezao","touchstart",function () {
			var boxheight = $(".shopcar").height();
			$(".shopcar").animate({
				bottom: -boxheight
			});
			$(this).fadeOut(300);
        });

        $(".removecar").on('touchstart', function () {
            var message = $(this).attr('alert-message'),
                url = $(this).attr('href'),
//                hl = $(".shopcarbox").find('ul').find('.c').length;
                hl = $(".shopcar").find('ul').find('.c').length;
            if (hl <= 0){
                show_message({status:0, message:'购物车是空的'});
                return;
            }
            layer.open({
                content: message
                , btn: ['确认', '取消']
                ,shadeClose: false
                , yes: function (index) {
                    layer.close(index);
                    blockUI.show('删除中...');
                    $.ajax(url, {
                        dataType:'json',
                        type:'get',
                        error:function(){
                            show_message({status:0, message:'请求超时'});
                            blockUI.hide();
                        },
                        timeout:60000,
                        success:function(data,textStatus,jqXHR){
                            show_message(data);
                            if(data.status == 1){
                                $(".zj").find('.min').remove();
                                $(".zj").find('.zi').remove();
                                var minConsume = $("#minConsume").val();
                                $(".shopcar").find('ul').html('');
                                $("#shopcarbtn").html('<img src="<?php echo $this->staticUrl?>img/png/pic85.png" alt="">');
                                $(".total").html('<p class="f10 cor9 lh10 mbmin">购物车是空的</p>');
                                $(".submit").html("<span>￥</span><span>"+minConsume+"起送</span>");
                                $(".submit").css('background','#999');
                                isTop = false;
                            }
                            blockUI.hide();
                            $(".shopcar").animate({
                                bottom: '-100%',
                            });
                            $(".zezao").fadeOut(300);
                        }
                    });
                }
            });
            return false;
        });

        /**
         * 去结算
         */
        $("body").delegate(".submit","touchstart",function ()  {
            var minConsume = $("#minConsume").val();
            var business = $("#business").val();
            var total = $("#total").val();
            if (Number(minConsume) > Number(total)){
                return;
                show_message({status:0, message:'不满足起送价'});
                return;
            }
            if(business == 1){
                show_message({status:0, message:'商家休息中，暂时无法接单'});
                return;
            }
            var l = $("#save-form").find('.c').length;
            if (!l){
                return;
                show_message({status:0, message:'购物车是空的'});
                return;
            }
            $(".status").each(function(){
                var status = $(this).text();
                if(status == 1){
                    show_message({status:0, message:$(this).parent().find('p:first').text() + '已下架'});
                    return;
                }
            });
            $("#save-form").submit();
        });

        //购物车高度控制
        function heightmol(){
            var onehight = $(".shopcar li:first-child").innerHeight();
            //alert(onehight);
            if($(".shopcar li").length>=5){
                $(".shopcar ul").css({"overflow":"auto","height":onehight*5});
            }
        }
		heightmol()
        /**
         * 添加修改数据
         * @param product_id        产品id
         * @param sort              规格id
         * @param tags              标签
         * @param quantity          数量
         * @param type              2 修改  1 添加
         * @param t                 2 加上原数量  1 不加原数量
         */
        function addMoel(product_id, sort, quantity, type, t,ob ='',tags='', first = false) {
            var url = '';
            if (type == 2){
                url = "<?php echo getUrl('cart/edit')?>";
            }else{
                url = "<?php echo getUrl('cart/add')?>";
            }
            $(".jiazai").show();
            $.ajax(url, {
                dataType:'json',
                type:'post',
                data:{product_id:product_id,sort:sort,quantity:quantity,type:t,tags:tags},
                error:function(){
                    blockUI.hide();
                    show_message({status:0, message:'请求超时'});
                },
                timeout:60000,
                success:function(e,textStatus,jqXHR){
                    blockUI.hide();
                    show_message(e);
                    if (e.status == 1) {
                        if (first == true){
                            var html = '<span class="min"></span><span class="zi">1</span>';
                            $(".quantity"+product_id).prepend(html);
                        }
                        each(e.data, product_id);
                    }else if(e.status == -1){
                        deleteCart(product_id, sort, true);
                    }else{
                        if(e.data.error_code == '00001'){
                            window.location.href = "<?php echo getUrl('user/login?merchant_id=')?>" + merchantId;
                        }
                        if(e.message.indexOf('已经下架')>-1){
                            deleteCart(product_id, sort);
                        }
                    }
                    $(".jiazai").hide();
                }
            });
            
        }

        function deleteCart(productId, sort, down = false) {
//            blockUI.show();
            $.ajax("<?php echo getUrl('cart/delete')?>", {
                dataType:'json',
                type:'post',
                data:{product_id:productId,sort:sort},
                error:function(){
                    blockUI.hide();
                    show_message({status:0, message:'请求超时'});
                },
                timeout:60000,
                success:function(e,textStatus,jqXHR){
                    blockUI.hide();
                    show_message(e);
					//$(".shopcar").animate({
						//bottom: 0
					//});
					//$(".zezao").fadeOut(300);
                    if (e.status == 1){
                        each(e.data, productId);
                        if(down){
                            //删除列表上的商品
                            $('.itemmodel').each(function () {
                                var dataid = $(this).find('.zengjian').attr('data-id');
                                if(parseInt(dataid) == parseInt(productId)){
                                    $(this).remove();
                                }
                            })
                        }
                    }
                }
            });
        }

        function each(data, product_id) {
            console.log(data);
            var shopcar = $(".shopcar"),
                lImg = "<?php echo $this->staticUrl?>img/png/pic86.png",
                aImg = "<?php echo $this->staticUrl?>img/png/pic85.png",
                html = '',
                n = 0,
                quantity = $(".quantity"+product_id),
                minConsume = $("#minConsume").val();

            if (data.list.length) {
                $.each(data.list, function (key, obj) {
                    if (product_id == obj.id) {
                        n = obj.quantity;
                    }
                    var tagStr = '';
                    if(obj.tags){
                        tagStr = '('+obj.tags+')';
                    }
                    html +=
                        '<li class="heng c">' +
                        '   <div class="">' +
                        '       <p class="lh10 f09">' + obj.name + '</p>' +
                        '       <p class="lh10"><span class="f07 cor9">' + obj.property_str + tagStr+ '</span></p>' +
                        '   </div>' +
                        '   <div class="heng vCenter">' +
                        '       <div class="price"><span class="szzz mr10 xian">¥ ' + obj.price + '</span></div>' +
                        '       <div class="zengjian zj" data-id="' + obj.id + '" data-sort="' + obj.sort + '">' +
                        '           <div class="min"></div>' +
                        '           <div class="zi">' + obj.quantity + '</div>' +
                        '           <div class="add"></div>' +
                        '       </div>' +
                        '   </div>' +
                        '   <input type="hidden" value="' + obj.id + '" name="product[' + key + '][product_id]">' +
                        '   <input type="hidden" value="' + obj.sort + '" name="product[' + key + '][sort]">' +
                        '   <input type="hidden" value="' + obj.tags + '" name="product[' + key + '][tags]">' +
                        '   <input type="hidden" value="' + obj.quantity + '" name="product[' + key + '][quantity]">' +
                        '</li>';
                });
                $("#shopcarbtn").html('<img src="' + lImg + '" alt=""><span class="weui-badge" style="position: absolute;top: 0;right: -2px;">' + data.number + '</span>');
                $(".total").html('<p class="f10 cor9 lh10 mbmin"><span class="mr5">共</span>¥'+data.total.toFixed(2)+'</p>');
                if (data.lunch_box_fee > 0) {
                    html +=
                        '<li class="heng">' +
                        '   <div class="">' +
                        '       <p class="lh10">打包费</p>' +
                        '   </div>' +
                        '   <div class="heng vCenter">' +
                        '       <span class="hongzi mr10">¥' + data.lunch_box_fee + '</span>' +
                        '   </div>' +
                        '</li>';
                }

            }else{
                $("#shopcarbtn").html('<img src="' + aImg + '" alt="">');
                $(".total").html('<p class="f10 cor9 lh10 mbmin">购物车是空的</p>');

            }
            if(n == 0){
                quantity.find('.zi').remove();
                quantity.find('.min').remove();
            }else{
                quantity.find('.zi').html(n);
            }
            if (Number(data.total) >= Number(minConsume)){
                $(".submit").html("<span>去结算</span>");
                $(".submit").css('background', '#2c53de');
            }else{

                $(".submit").html("<span>￥</span><span>"+minConsume+"起送</span>");
                $(".submit").css('background', '#999');
            }
            $("#total").val(data.total.toFixed(2));
            shopcar.find('ul').html(html);
            $(".guigemero").animate({top:'100%'});
            isTop = true;
//            shopCarBtn();
        }
    });

    //弹出的选项框选中之后的回调
    function setChoice(res){
//        console.log(res)
        choice = res;//设置
        $('#price_zyl').text(res.data.price);
        $('#quantity_zyl').text(res.data.quantity)
    }

    //一个也没选
    function setBase(){
//        console.log(res)
        choice = {}//重置
        $('#price_zyl').text(base.data.price);
        $('#quantity_zyl').text(base.data.quantity)
    }
</script>